<?php
/**
 * 注意：本内容仅限于博也公司内部传阅,禁止外泄以及用于其他的商业目的
 * @author    hebidu<346551990@qq.com>
 * @copyright 2018 www.itboye.com Boye Inc. All rights reserved.
 * @link      http://www.itboye.com/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 * Revision History Version
 ********1.0.0********************
 * file created @ 2018-03-13 10:05
 *********************************
 ********1.0.1********************
 *
 *********************************
 */

namespace by\component\tailong_bank\api;


use by\component\tailong_bank\context\BaseContext;
use by\component\tailong_bank\helper\AesHelper;
use by\component\tailong_bank\req\ProxyBussDevelopQrcReq;
use by\component\tailong_bank\resp\ProxyBussDevelopQrcResp;
use by\infrastructure\helper\CallResultHelper;
use Psr\SimpleCache\CacheInterface;

class ProxyBussDevelopQrcApi extends BaseApi
{
    public function __construct(CacheInterface $cache = null)
    {
        parent::__construct($cache);
        $this->setService("zjjr/proxyBussDevelopQrc");
    }

    /**
     * @param $appAccessToken
     * @param ProxyBussDevelopQrcReq $req
     * @param BaseContext $context
     * @return \by\infrastructure\base\CallResult
     * @throws \ErrorException
     */
    public function call($appAccessToken, ProxyBussDevelopQrcReq $req, BaseContext $context)
    {
        $url = $context->getApiUrl().$this->getService();
        $reqData = $req->toArray();
        $data = [
            'appID' => $context->getAppID(),
            'encryptMethod' => 'AES',
            'seqNO' => $req->getSeqNo(),
            'signMethod' => 'MD5',
            'reqData' => $reqData,
        ];
        $data['appAccessToken'] = $appAccessToken;
        $strReqData = json_encode($reqData, JSON_UNESCAPED_UNICODE);
        $data['sign'] = strtoupper(md5($strReqData . $req->getSeqNo() . $context->getAppSecretKey()));
        $aesKey = strtoupper(md5($req->getSeqNo() . $appAccessToken . $context->getAppSecretKey()));
        $data['reqData'] = $this->encrypt($data, $aesKey);
        $result = $this->post($url, json_encode($data, JSON_UNESCAPED_UNICODE));
        if ($result->isFail()) return $result;
        $rspData = $result->getData();
        if (is_string($rspData)) {
            $rspData = json_decode($rspData, JSON_OBJECT_AS_ARRAY);
        }
        if (!is_array($rspData)) {
            CallResultHelper::fail('[ZhuJia]响应数据格式错误,请重试', $rspData);
        }
        if (!$this->checkSign($rspData, $context->getAppSecretKey())) {
            CallResultHelper::fail('[ZhuJia]验签失败,请重试');
        }
        $decryptRspData = AesHelper::opensslDecrypt($rspData['rspData'], $aesKey);
        $rspData['_rspData'] = json_decode($decryptRspData, JSON_OBJECT_AS_ARRAY);
        $resp = new ProxyBussDevelopQrcResp($rspData);
        if ($resp->isFail()) {
            return CallResultHelper::fail($resp->getErrorMsg(), $resp);
        }
        return CallResultHelper::success($resp);
    }
}